import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import {
  Tag,
  Button,
  Card,
  Col,
  Form,
  Icon,
  Input,
  Row,
  Select,
  Switch,
  Divider,
  Modal,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
const FormItem = Form.Item;
const { Option } = Select;
@connect(
  state => ({
    dataqueryTableList: state.infoShow.dataqueryTableList,
    dataqueryDbNameList: state.infoShow.dataqueryDbNameList,
    dataqueryTableNameList: state.infoShow.dataqueryTableNameList,
    dataqueryNameList: state.infoShow.dataqueryNameList,
    loadingqueryTableList: state.loading.effects['infoShow/queryTableList'],
    loadingqueryDbNameList: state.loading.effects['infoShow/queryDbNameList'],
    loadingqueryTableNameList: state.loading.effects['infoShow/queryTableNameList'],
    loadingqueryNameList: state.loading.effects['infoShow/queryNameList'],
  }),
  dispatch => ({
    queryTableList: e => dispatch({ type: 'infoShow/queryTableList', payload: e }),
    savequeryTableList: e => dispatch({ type: 'infoShow/savequeryTableList', payload: e }),
    queryDbNameList: e => dispatch({ type: 'infoShow/queryDbNameList', payload: e }),
    queryTableNameList: e => dispatch({ type: 'infoShow/queryTableNameList', payload: e }),
    queryNameList: e => dispatch({ type: 'infoShow/queryNameList', payload: e }),
  })
)
@Form.create()
class infoShow extends PureComponent {
  state = {
    selectedRows: [],
    showSensitiveInfo: false,
  };

  dbNameColumns = [
    {
      title: '数据库名',
      dataIndex: 'dbName',
    },
    {
      title: 'IP地址',
      dataIndex: 'dbIp',
    },
  ];

  expandedRowRender = props => {
    const { text } = this.state;
    return (
      <Fragment>
        <TableList
          className={styles.tdPadding}
          selectedRows={this.state.selectedRows}
          columns={[
            {
              title: '表名',
              dataIndex: 'tableName',
            },
            {
              title: '敏感标签',
              dataIndex: 'sensLabel',
              render: sensLabel =>
                sensLabel &&
                sensLabel.split(',').map(item => (
                  <Tag color="red" key={item}>
                    {item}
                  </Tag>
                )),
            },
            {
              title: '数据分类',
              dataIndex: 'typeCode',
              render: typeCode => typeCode && typeCode.split(',')[0],
            },
            {
              title: '分级名称',
              dataIndex: 'levelName',
              render: levelName => levelName && levelName.split(',')[0],
            },
            {
              title: '操作',
              render: text => (
                <Fragment>
                  <ViewCols
                    {...{ dbId: props.dbId, text, matchNums: this.state.showSensitiveInfo }}
                  >
                    <a>查看列</a>
                  </ViewCols>
                </Fragment>
              ),
            },
          ]}
          data={{ dataList: props.tableLists }}
          //onChange={this.handleStandardTableChange.bind(this)}
          rowKey={record => record.id}
          pagination={false}
          hideRowSelection
        />
      </Fragment>
    );
  };

  componentDidMount() {
    this.pageTableList();
    this.props.queryDbNameList();
    this.props.queryTableNameList();
    this.props.queryNameList();
  }
  componentWillUnmount() {
    this.props.savequeryTableList([]);
  }
  // 分页查询列表
  pageTableList(res, pageSize = 10, pageNum = 0) {
    const values = {
      ...this.state.formValues,
      matchNums: this.state.showSensitiveInfo == false ? '' : 0,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    this.props.queryTableList(values);
  }
  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageTableList(formValues, pagination.pageSize, pagination.current - 1);
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState(
        {
          formValues: values,
        },
        this.pageTableList
      );
    });
  };

  switchChange = checked => {
    this.setState({ showSensitiveInfo: checked }, () => {
      this.pageTableList();
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="数据库名称">
              {getFieldDecorator('dbId')(
                <Select
                  placeholder="请选择"
                  loading={this.props.loadingqueryDbNameList}
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  {this.props.dataqueryDbNameList.map(item => (
                    <Option value={item.dbId} key={item.dbId}>
                      {item.dbName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="数据库表名">
              {getFieldDecorator('tableName')(
                <Select
                  placeholder="请选择"
                  loading={this.props.loadingqueryTableNameList}
                  allowClear
                  showSearch
                >
                  {this.props.dataqueryTableNameList.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          {/* <Col md={7} sm={24}>
            <FormItem label="敏感分级">
              {getFieldDecorator('level')(
                <Select placeholder="请选择" loading={this.props.loadingqueryNameList} allowClear>
                  {this.props.dataqueryNameList.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col> */}

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { selectedRows } = this.state;
    const { loadingqueryTableList, dataqueryTableList } = this.props;

    return (
      <PageHeaderWrapper title="敏感信息展现">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Switch
              checkedChildren="显示敏感信息"
              unCheckedChildren="隐藏敏感信息"
              onChange={this.switchChange}
              checked={this.state.showSensitiveInfo}
              style={{ marginBottom: 16 }}
            />
            <br />
            <TableList
              className={styles.tdPadding}
              defaultExpandAllRows
              selectedRows={selectedRows}
              loading={loadingqueryTableList}
              data={dataqueryTableList}
              columns={this.dbNameColumns}
              expandedRowRender={this.expandedRowRender}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.dbId}
              hideRowSelection
              // pagination={false}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

//查看详情弹窗
@connect(
  state => ({
    dataqueryColumnList: state.infoShow.dataqueryColumnList,
    loadingqueryColumnList: state.loading.effects['infoShow/queryColumnList'],
  }),
  dispatch => ({
    queryColumnList: e => dispatch({ type: 'infoShow/queryColumnList', payload: e }),
    savequeryColumnList: e => dispatch({ type: 'infoShow/savequeryColumnList', payload: e }),
  })
)
class ViewColsShell extends PureComponent {
  state = {
    selectedRows: [],
  };
  colColumns = [
    {
      title: '列名',
      dataIndex: 'columnName',
    },
    {
      title: '敏感字段',
      dataIndex: 'label',
    },

    {
      title: '列备注',
      dataIndex: 'remark',
    },
  ];
  // 数据库列名-分页查询列表
  pageColsList = (res = {}, pageSize = 10, pageNum = 0) => {
    const values = {
      dbId: this.props.dbId,
      tableName: this.props.text.tableName,
      matchNums: this.props.matchNums == false ? '' : 0,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    this.props.queryColumnList(values);
  };
  componentDidMount() {
    this.pageColsList();
  }

  componentWillUnmount() {
    this.props.savequeryColumnList({
      dataList: [],
      pageNum: 0,
      pageSize: 0,
      totalCount: 0,
    });
  }

  handleStandardColumnChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageColsList(formValues, pagination.pageSize, pagination.current - 1);
  }
  render() {
    const { dataqueryColumnList } = this.props;
    return (
      <TableList
        bordered
        className={styles.tdPadding}
        selectedRows={this.state.selectedRows}
        loading={this.props.loadingqueryColumnList}
        data={dataqueryColumnList}
        columns={this.colColumns}
        onChange={this.handleStandardColumnChange.bind(this)}
        rowKey={record => record.id}
        hideRowSelection
      />
    );
  }
}

class ViewCols extends PureComponent {
  constructor(props) {
    super(props);
  }
  state = {
    viewColsModalVisible: false,
  };
  handleViewColsModalVisible = flag => {
    this.setState({
      viewColsModalVisible: !!flag,
    });
  };

  render() {
    const { text } = this.props;
    return (
      <>
        <Modal
          destroyOnClose
          width={800}
          title="查看列"
          visible={this.state.viewColsModalVisible}
          onCancel={() => this.handleViewColsModalVisible(false)}
          footer={[
            <Button key="back" type="primary" onClick={() => this.handleViewColsModalVisible()}>
              返回
            </Button>,
          ]}
          // className={styles.viewMore}
        >
          <div style={{ marginBottom: 16 }}>表名：{this.props.text.tableName}</div>
          <ViewColsShell {...this.props} />
        </Modal>
        <span onClick={() => this.handleViewColsModalVisible(true)}>{this.props.children}</span>
      </>
    );
  }
}

export default infoShow;
